import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Button, Tools, Icon, Modal,  } from 'weaver-mobile';
import { ListViewPage, ListEditable, Upload } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import NoData from '../../../public/NoData';
import MeetingUtil from '../../../util/meetingUtil';
const getLabel = Tools.getLabel;
const List = ListEditable.List

@inject('viewMeetingStore')
@withRouter
@observer
class ServiceView extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            addtopic: true
        };
      }
    componentDidMount() {
      const { meetingServiceDefaultValue} = this.props.viewMeetingStore;
      this.getDetail();
      //if(meetingServiceDefaultValue == 1) this.addEditTableNew()
    }

    componentWillReceiveProps (nextProps) {
      const {getBaseDetail,setState} = this.props.viewMeetingStore;
      if(getBaseDetail){
        this.getDetail();
        setState({getBaseDetail:false})
      }
    }

    getDetail = ()=>{
      const { getService, meetingId, get_Data, get_Conditions,is_service,setState, type, initServiceList,accessoryBaseInfo  } = this.props.viewMeetingStore;
      
        //考虑到刷新的时候
        let typeTemp = type?type:sessionStorage.getItem('type')
        let meetingIdTemp = meetingIdTemp?meetingIdTemp:sessionStorage.getItem('meetingId')
        
        if(meetingIdTemp === null) {
          meetingIdTemp = ''
        }
        
        setState({type:typeTemp,meetingId:meetingIdTemp})
        const options = {
            url: '/api/meeting/field/getMeetingServiceField',
            method: 'POST',
            params: { meetingid: meetingIdTemp,ismobile:'1' },
            type: 'json',
          };
          // typeTemp === 'view' && getService(options);
          initServiceList();
          get_Data({meetingid: meetingIdTemp}, 'service');
          get_Conditions({meetingid: meetingIdTemp, secId:accessoryBaseInfo.category}, 'service');
          setState({is_service: false})
        
    }

    addEditTable = () => {
        const pathname = this.props.location.pathname;
        const { service_list } = this.props.viewMeetingStore;
        service_list.doAdd('',this.onchange);
        this.props.history.push(`${pathname}/editor`);
    }

    addEditTableNew = () => {
      const pathname = this.props.location.pathname;
      const { service_list } = this.props.viewMeetingStore;
      service_list.doAdd('',this.onchange);
      //this.props.history.push(`${pathname}/editor`);
  }

    onchange = (newData) => {
      let {setState, service_list, tempServiceUploadStore} = this.props.viewMeetingStore;
      let obj = {};
      service_list = toJS(service_list);
      if (service_list && service_list.formList) {
        for(let i in service_list.formList) {
          obj = {
            ...obj,
            [i]: service_list.formList[i].uploadFiles
          }
        }
      }
      setState({ serivce_data: newData,serivce_initialData:newData, tempServiceUploadStore: obj });
    }

    willEdit = (arg) => {
      const {setState, getService_project_hrminfo} = this.props.viewMeetingStore;
      if (arg) {
        let {setState, service_list, tempServiceUploadStore} = this.props.viewMeetingStore;
        let obj = {};
        service_list = toJS(service_list);
        if (service_list && service_list.formList) {
          for(let i in service_list.formList) {
            obj = {
              ...obj,
              [i]: service_list.formList[i].uploadFiles
            }
          }
        }

        setState({ serivce_data: arg[0],serivce_initialData:arg[0], tempServiceUploadStore: obj });
        if (arg[1] && arg[1].domkey && arg[1].domkey[0] === 'items_46') {
          let itemsIdObj = arg[2]
          let itemIds = itemsIdObj && itemsIdObj.map(item=>item.id)
          let hrmmembers = '' ;
          arg[0].map(v => {
            if (service_list.editingKey === v.id) {
              hrmmembers = v.hrmids_47;
            }
          })
          arg[2] && arg[2][0] && getService_project_hrminfo({items: itemIds.join(','),hrmmembers:hrmmembers}) // 选择服务带出服务人员
        }
      }
    }

    itemChange = (content, condition, data, index) => {
      let {serivce_data, tempServiceUploadStore,meetingId } = this.props.viewMeetingStore;
      tempServiceUploadStore = toJS(tempServiceUploadStore);
      content = toJS(content);

      if(condition.conditionType == 'CHECKBOX' && serivce_data.length > 0){
        if(content == 1){
          return getLabel(163,'是')
        }else{
          return getLabel(161,'否')
        }
      }
      // else if (condition.conditionType == 'UPLOAD') {
      //   let uploadDatas = content || [];
      //   for(let j in data) {// 由于上传附件的字段名由后台自定义，因此用该方法判断字段名
      //     if (tempServiceUploadStore[data.id] && tempServiceUploadStore[data.id][j]) {
      //       uploadDatas = tempServiceUploadStore[data.id][j];
      //     }
      //   }
      //   return (
      //     <Upload
      //       datas={uploadDatas}
      //       viewAttr={1}
      //       previewOfAttachParams={{meetingid:meetingId,fromModule:'meeting'}}
      //     >
      //     </Upload>)
      // } 
      else {
        return content;
      }
    }

    willCopyData = (allData, copyIds, newData ) => {
      let { serivce_data, setState, serviceConditionUploadKeys } = this.props.viewMeetingStore;
      let old_datas = toJS(serivce_data);
      let temp_serviceConditionUploadKeys = toJS(serviceConditionUploadKeys);
      copyIds = toJS(copyIds);
      if(temp_serviceConditionUploadKeys.length > 0 && Array.isArray(newData)) {
        Array.isArray(temp_serviceConditionUploadKeys) && temp_serviceConditionUploadKeys.forEach(keys => {
          let tempNewData = [];
          newData.forEach((element, _index) => {
            if(Array.isArray(old_datas)) {
              let copyParentData = old_datas.find(v =>  v.id === copyIds[_index]);
              if(copyParentData) {
                copyParentData = {
                  ...copyParentData,
                  id: element.id,
                  key: element.id,
                  randomFieldId: element.id,
                };
                element = {
                  ...element,
                  ...copyParentData
                };
              }
            }
            tempNewData.push(element);
          });
          old_datas = old_datas.concat(tempNewData);
        }) 
      }
      setState({ serivce_data: old_datas });
    }

    createService = () => {
        const { service_list, serivce_data, serivce_initialData, service_conditions, setState,  } = this.props.viewMeetingStore;
        let field = [];
        let addVisible = serivce_data && serivce_data.length === 0 ? 'none' : 'block';
        field.push(
          <div className='topic-list' key='topic-list' style={{display: addVisible}}>
             {service_conditions&&<ListEditable
                title={getLabel(501095,"编辑服务内容")}
                rowKey="id"
                store={service_list}
                data={serivce_data}
                initialData={serivce_initialData}
                conditions={toJS(service_conditions)}
                onChange={this.onchange}
                willCopy={this.willCopyData}
                getItemContent={(content, condition, data, index)=>{return this.itemChange(content, condition, data, index)}}
                willDelete={newData => new Promise((resolve) => {
                    Modal.alert(getLabel(15097,'确定要删除吗？'), '', [
                    { text: getLabel(31129,'取消'), onPress: () => resolve(false)},
                    {
                        text:  getLabel(826,'确定'),
                        onPress: () => {
                        resolve(newData);
                        },
                    },
                    ]);
                })}
                willEdit={(...arg) => {this.willEdit(arg)}}
                />
              }
          </div>
        )

        serivce_data && serivce_data.length === 0 && field.push(
            <div className='topic-nodata' key='topic-nodata'>
                <div className='icon'>
                    <Icon type='meeting-add-meeting' size='lg'/>
                </div>
                <label>{getLabel(501096,'在这里，你可以添加会议服务')}</label>
                <div className='btn-tianjia'>
                    <Button type='primary' onClick={() => {this.addEditTable()}}>{getLabel(384113,'添加')}</Button>
                </div>
            </div>
        )

        return field;
    }

    getLoading = () => {
      return (
        <div className='loaidng-icon' key='loading' style={{position: 'fixed', left: '50%', top: '50%'}}>
          <Icon type='loading' size='lg'/>
        </div>
      );
    }

    render() {
        const { serviceList,service_list, type , btns,service_conditions, serivce_data, loadding } = this.props.viewMeetingStore;
        const { addtopic } = this.state;
        const serviceHeight = this.getHeight();
        return (
        <div className={btns&&btns.length===1&&btns[0]==='doViewLog'?"topic-service-content tabContentHeight2":'topic-service-content tabContentHeight'}>
          <div className={'serviceFormDiv'} serivce_data={serivce_data}>
          {loadding && this.getLoading()}
            {
            type === 'view' ?
            serviceList.data.length===0?<NoData />:
            (service_conditions&&<List
                  mainStore={service_list}
                  tableStore={service_list}
                  store={serviceList}
                  onRowSelect = {()=>{return;}}
                  onRowClick = {()=>{return;}}
                  conditions = {service_conditions}
                  getItemContent={(content, condition, data, index) => {return this.itemChange(content, condition, data, index)}}
                />
            )
            :
                this.createService()
               
            }
            </div>
        </div>
        )
    }

    getHeight = () => {
      return document.body.clientHeight - MeetingUtil.getTabHeight();
    }
}

export default ServiceView;